<template>
  <div class="lix-container">
    <div class="lix-pub__formwrap">
      <div class="lix-pub__category">
        <div class="title">活动分类：</div>
        <div class="list">
          <div v-for="(item, idx) in categoryList" :key="idx" @click="selectCategory" :data-idx="idx" :class="[idx === selectCateIdx ? 'item active' : 'item']">
            {{ item.key }}
          </div>
        </div>
      </div>
      <div class="lix-pub__address">
        <div class="title">
          活动地点：
        </div>
        <div class="address-wrap">
          <div class="select" @click="showMulLinkageThreePicker">
            <p>{{ areaData }}</p>
            <image src="../../static/image/down.png" />
          </div>
          <textarea placeholder="请输入详细地址" placeholder-class="lix-pub__placeholder" @input="textareaInput"/>
        </div>
      </div>
      <div class="lix-pub__time">
        <div class="title">
          计划时间：
        </div>
        <div class="select" @click="showTimePicker">
          <p>{{ timeData }}</p>
          <image src="../../static/image/down.png" />
        </div>
      </div>
      <div class="lix-pub__age">
        <div class="title">
          参与年龄：
        </div>
        <div class="select" @click="showFirstAgePicker">
          <p>{{ firstAgeData }}</p>
          <image src="../../static/image/down.png" />
        </div>
        <div class="seperate">-</div>
        <div class="select" @click="showSecondAgePicker">
          <p>{{ secondAgeData }}</p>
          <image src="../../static/image/down.png" />
        </div>
      </div>
      <div class="lix-pub__age">
        <div class="title">
          参与人数：
        </div>
        <div class="select" @click="showLimitMinPicker">
          <p>{{ limitMin }}</p>
          <image src="../../static/image/down.png" />
        </div>
        <div class="seperate">-</div>
        <div class="select" @click="showLimitMaxPicker">
          <p>{{ limitMax }}</p>
          <image src="../../static/image/down.png" />
        </div>
      </div>
      <div class="lix-pub__name">
        <div class="title">
          联系人：
        </div>
        <div class="input">
          <input type="text" placeholder="请输入联系人称呼" placeholder-class="lix-pub__placeholder" @input="nameInput"/>
        </div>
      </div>
      <div class="lix-pub__phone">
        <div class="title">
          联系方式：
        </div>
        <div class="input">
          <input type="text" placeholder="请输入手机号码" placeholder-class="lix-pub__placeholder" @input="phoneNumerInput"/>
          <button @click="validateCodeAction" :disabled="isClick">{{ timeBtnData }}</button>
        </div>
      </div>
      <div class="lix-pub__name">
        <div class="title">
          验证码：
        </div>
        <div class="input">
          <input type="text" placeholder="请输入验证码" placeholder-class="lix-pub__placeholder" @input="validateCodeInput"/>
        </div>
      </div>
    </div>
    <div class="lix-pub__submit">
      <button @click="submit">发布需求</button>
    </div>
    <mpvue-picker ref="mpvuePicker" :mode="mode" :deepLength="deepLength" :pickerValueDefault="pickerValueDefault" @onChange="onChange" @onConfirm="onConfirm" @onCancle="onCancel" :pickerValueArray="pickerValueArray"></mpvue-picker>
    <mpvue-city-picker ref="mpvueCityPicker" :pickerValueDefault="pickerValueDefault" @onChange="onChange" @onCancel="onCancel" @onConfirm="onConfirm"></mpvue-city-picker>
  </div>
</template>

<script>
import mpvuePicker from 'mpvue-picker';
import mpvueCityPicker from 'mpvue-citypicker';
import { cityObjs } from '../../utils/area';
import Tip from '../../utils/tips';
import { publishCourseApi, getSMSCode } from '../../api';
const date = new Date();
const years = [];
const months = [];
const days = [];
const hours = [];
const minutes = [];

for (let i = 0; i < 5; i++) {
  years.push({ label: i + date.getFullYear() + '年', value: i + date.getFullYear() });
}

for (let i = 1; i <= 12; i++) {
  const val = i < 10 ? '0' + i : i;
  months.push({ label: val + '月', value: val });
}

for (let i = 1; i <= 31; i++) {
  const val = i < 10 ? '0' + i : i;
  days.push({ label: val + '日', value: val });
}

for (let i = 0; i < 24; i++) {
  const val = i < 10 ? '0' + i : i;
  hours.push({ label: val + '时', value: val });
}

for (let i = 0; i < 60; i++) {
  const val = i < 10 ? '0' + i : i;
  minutes.push({ label: val + '分', value: val });
}

const ages = [];
for (let i = 0; i < 108; i++) {
  ages.push({ label: i, value: i });
}

const peoples = [];
for (let i = 1; i < 1000; i++) {
  peoples.push({ label: i, value: i });
}

let interval = null;
export default {
  components: {
    mpvuePicker,
    mpvueCityPicker
  },
  data() {
    return {
      categoryList: [
        {id: 1, key: '书法绘画'},
        {id: 2, key: '英语口才'},
        {id: 3, key: '舞蹈跆拳'},
        {id: 4, key: '音乐戏剧'},
        {id: 5, key: '国象围棋'},
        {id: 6, key: '科学探索'},
        {id: 7, key: '学科辅导'},
        {id: 8, key: '亲子活动'}
      ],
      selectCateIdx: null, // 分类选择选中的idx
      pickerType: null, // 三种类型选择器的type
      areaData: '请选择', // 地区label
      timeData: '请选择', // 计划时间label
      firstAgeData: '请选择', // 第一个参与年龄
      secondAgeData: '请选择', // 第二个参与年龄
      nameText: '', // 联系人姓名
      phoneText: '', // 联系方式
      codeText: '', // 验证码数据
      mode: 'selector',
      cityData: cityObjs,
      deepLength: 0, // 几级联动
      pickerValueDefault: [0, 0, 0], // 初始化值
      pickerValueArray: [], // picker 数组值
      isClick: false,
      currentTime: 60,
      timeBtnData: '获取验证码',
      // 接口上传需要的数据
      catrgorys: null,
      province: null,
      city: null,
      district: null,
      addressDetail: null,
      limitMin: '请选择',
      limitMax: '请选择'
    };
  },
  methods: {
    // 课程分类 点击选择事件
    selectCategory(e) {
      const idx = e.mp.currentTarget.dataset.idx;
      this.selectCateIdx = idx;
      this.categorys = this.categoryList[idx].id + '';
    },
    onChange(e) {
      console.log(e);
    },
    onCancel(e) {
      console.log(e);
    },
    onConfirm(e) {
      console.log(e);
      const value = e.label;
      switch (this.pickerType) {
        case 'area':
          console.log('地址选择数据');
          const array = value.split('-');
          console.log(array);
          this.areaData = array[0] + array[1] + array[2];
          const cityCode = e.cityCode;
          this.province = cityCode.slice(0, 2) + '0000';
          this.city = cityCode.slice(0, 4) + '00';
          this.district = cityCode;
          break;
        case 'time':
          const valArr = e.value;
          const date = this.getDateFormatter(valArr);
          console.log('日期选择数据: ', date);
          this.timeData = date;
          break;
        case 'firstAge':
          console.log('第一年龄选择数据');
          this.firstAgeData = value;
          break;
        case 'secondAge':
          console.log('第二年龄选择数据');
          this.secondAgeData = value;
          break;
        case 'limitMin':
          console.log('最小参与人数选择数据');
          this.limitMin = value;
          break;
        case 'limitMax':
          console.log('最大参与人数选择数据');
          this.limitMax = value;
          break;
      }
    },
    getDateFormatter(valArr) {
      const year = years[valArr[0]].value;
      const month = months[valArr[1]].value;
      const day = days[valArr[2]].value;
      const hour = hours[valArr[3]].value;
      const minute = minutes[valArr[4]].value;

      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    },
    showMulLinkageThreePicker() {
      this.pickerType = 'area';
      this.pickerValueDefault = [0, 0, 1];
      this.$refs.mpvueCityPicker.show();
    },
    showTimePicker() {
      this.pickerType = 'time';
      this.mode = 'multiSelector';
      this.pickerValueArray = [
        years,
        months,
        days,
        hours,
        minutes
      ];
      this.$refs.mpvuePicker.show();
    },
    showFirstAgePicker() {
      this.pickerType = 'firstAge';
      this.pickerValueArray = ages;
      this.mode = 'selector';
      this.$refs.mpvuePicker.show();
    },
    showSecondAgePicker() {
      this.pickerType = 'secondAge';
      this.pickerValueArray = ages;
      this.mode = 'selector';
      this.$refs.mpvuePicker.show();
    },
    showLimitMinPicker() {
      this.pickerType = 'limitMin';
      this.pickerValueArray = peoples;
      this.mode = 'selector';
      this.$refs.mpvuePicker.show();
    },
    showLimitMaxPicker() {
      this.pickerType = 'limitMax';
      this.pickerValueArray = peoples;
      this.mode = 'selector';
      this.$refs.mpvuePicker.show();
    },
    textareaInput(e) {
      const value = e.mp.detail.value;
      this.addressDetail = value;
      console.log(value);
    },
    nameInput(e) {
      const value = e.mp.detail.value;
      this.nameText = value;
      console.log(this.nameText);
    },
    phoneNumerInput(e) {
      const value = e.mp.detail.value;
      this.phoneText = value;
      console.log(this.phoneText);
    },
    validateCodeInput(e) {
      const value = e.mp.detail.value;
      this.codeText = value;
      console.log(this.codeText);
    },
    validateCodeAction(e) {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (this.phoneText.length === 0) {
        Tip.error('手机号码不能为空');
        return;
      }

      if (this.phoneText.length !== 11) {
        Tip.error('手机号码长度有误');
        return;
      }

      if (!phoneReg.test(this.phoneText)) {
        Tip.error('不合法的手机号码');
        return;
      }

      const self = this;
      // 获取短信验证码接口
      getSMSCode({
        mobile: this.phoneText,
        scope: 'publish'
      }).then(res => {
        console.log(res);
        // 禁止获取验证码的点击
        self.isClick = true;
        let currentTime = self.currentTime;
        interval = setInterval(function() {
          currentTime -= 1;
          self.timeBtnData = currentTime + '秒后获取';
          if (currentTime <= 0) {
            clearInterval(interval);
            self.timeBtnData = '获取验证码';
            self.currentTime = 60;
            self.isClick = false;
          }
        }, 1000);
      });
    },
    submit(e) {
      if (!this.validateForm()) {
        return;
      }
      const params = {
        categorys: this.categorys,
        province: this.province,
        city: this.city,
        district: this.district,
        address_detail: this.addressDetail,
        begin_date: this.timeData,
        age_min: this.firstAgeData,
        age_max: this.secondAgeData,
        limit_min: this.limitMin,
        limit_max: this.limitMax,
        contact: this.nameText,
        mobile: this.phoneText,
        code: this.codeText
      };

      publishCourseApi(params)
        .then(response => {
          console.log(response);
          wx.showModal({
            title: '发布成功',
            content: response.data.message,
            success: function(res) {
              wx.navigateBack();
            }
          });
        });

      console.log(params);
      console.log('发布需求');
    },
    validateForm() {
      if (this.selectCateIdx === null) {
        Tip.error('请选择活动分类');
        return false;
      }
      if (this.areaData === '请选择') {
        Tip.error('请选择活动地点');
        return false;
      }
      if (this.addressDetail === null) {
        Tip.error('请填写详细地址');
        return false;
      }
      if (this.timeData === '请选择') {
        Tip.error('请选择活动时间');
        return false;
      }
      if (this.firstAgeData === '请选择' || this.secondAgeData === '请选择') {
        Tip.error('请正确选择参与年龄');
        return false;
      }
      if (this.limitMin === '请选择' || this.limitMax === '请选择') {
        Tip.error('请正确选择参与人数');
        return false;
      }
      if (this.nameText.length < 1) {
        Tip.error('请输入联系人称呼');
        return false;
      }
      if (this.phoneText.length < 10) {
        Tip.error('请输入正确的手机号码');
        return false;
      }
      if (this.codeText.length < 1) {
        Tip.error('请输入短信验证码');
        return false;
      }

      return true;
    }
  }
};
</script>

<style lang="scss">
@import "../../theme-chalk/publish.scss";
</style>
